#!/usr/bin/env python
"""
创建管理员用户脚本
用于创建具有管理员权限的用户，用于访问后台管理系统
"""

import os
import sys
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pecco_backend.settings')
django.setup()

from django.contrib.auth.models import User
from pecco_site.models import UserProfile


def create_admin_user():
    """创建管理员用户"""
    
    print("=== PECCO Admin User Creation ===")
    print()
    
    # 获取用户输入
    username = input("Enter admin username (default: admin): ").strip() or "admin"
    email = input("Enter admin email: ").strip()
    
    if not email:
        print("Error: Email is required!")
        return False
    
    # 检查用户是否已存在
    if User.objects.filter(username=username).exists():
        print(f"Error: User '{username}' already exists!")
        
        # 询问是否更新现有用户为管理员
        update = input("Do you want to make this user an admin? (y/N): ").strip().lower()
        if update == 'y':
            user = User.objects.get(username=username)
            user.is_staff = True
            user.is_superuser = True
            user.email = email
            user.save()
            
            # 确保有UserProfile
            profile, created = UserProfile.objects.get_or_create(user=user)
            
            print(f"✅ User '{username}' has been updated to admin status!")
            return True
        else:
            return False
    
    if User.objects.filter(email=email).exists():
        print(f"Error: Email '{email}' is already registered!")
        return False
    
    # 获取密码
    import getpass
    password = getpass.getpass("Enter admin password: ")
    confirm_password = getpass.getpass("Confirm password: ")
    
    if password != confirm_password:
        print("Error: Passwords do not match!")
        return False
    
    if len(password) < 6:
        print("Error: Password must be at least 6 characters long!")
        return False
    
    try:
        # 创建管理员用户
        user = User.objects.create_user(
            username=username,
            email=email,
            password=password,
            is_staff=True,      # 管理员权限
            is_superuser=True   # 超级管理员权限
        )
        
        # 创建用户资料
        UserProfile.objects.create(
            user=user,
            newsletter_subscribed=False
        )
        
        print()
        print("✅ Admin user created successfully!")
        print(f"   Username: {username}")
        print(f"   Email: {email}")
        print(f"   Admin Access: ✅ Yes")
        print(f"   Superuser: ✅ Yes")
        print()
        print("You can now login to the admin panel at:")
        print("   http://127.0.0.1:5173/")
        print()
        
        return True
        
    except Exception as e:
        print(f"Error creating admin user: {e}")
        return False


def list_admin_users():
    """列出所有管理员用户"""
    print("=== Current Admin Users ===")
    print()
    
    admin_users = User.objects.filter(is_staff=True)
    
    if not admin_users.exists():
        print("❌ No admin users found!")
        print("   Please create an admin user to access the management system.")
    else:
        print(f"Found {admin_users.count()} admin user(s):")
        print()
        
        for user in admin_users:
            print(f"👤 {user.username}")
            print(f"   Email: {user.email}")
            print(f"   Staff: {'✅' if user.is_staff else '❌'}")
            print(f"   Superuser: {'✅' if user.is_superuser else '❌'}")
            print(f"   Active: {'✅' if user.is_active else '❌'}")
            print(f"   Last Login: {user.last_login or 'Never'}")
            print()


def main():
    """主函数"""
    if len(sys.argv) > 1 and sys.argv[1] == 'list':
        list_admin_users()
    else:
        if not create_admin_user():
            sys.exit(1)


if __name__ == '__main__':
    main()

